<?php

namespace app\api\controller;


use app\admin\model\HouseOwnerModel;
use app\admin\model\StaffModel;
use app\admin\model\UserLoginLogModel;
use app\common\controller\Api;
use app\common\library\Auth;
use fast\Random;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\Validate;


class Staff extends Api
{

    protected $noNeedRight = '*';


    public function index()
    {
        $page_size = $this->request->param('page_size', 10);
        $kw = $this->request->param('kw', '');
        $where = [];
        if (!empty($kw)) {
            $where['name'] = ['like', '%' . $kw . '%'];
        }
        $list = StaffModel::where('user_id', $this->auth->id)
            ->where($where)
            ->field('id,name,mobile,role,create_time')
            ->paginate($page_size)->each(function ($item) {
                $item->append(['role_text', 'create_time_text']);
            });

        $this->success('success', $list);
    }

    public function add()
    {
        $params = $this->request->post();
        unset($params['id']);
        $checkRes = $this->validate($params, [
            'name|姓名' => 'require',
            'sex|性别' => 'require|in:1,2',
            'mobile|手机号' => 'require',
            'role|角色' => 'require|in:1,2',
        ]);
        if ($checkRes !== true) {
            $this->error($checkRes);
        }
        if (!Validate::regex($params['mobile'], "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }

        if ($this->auth->mobile == $params['mobile']) {
            $this->error('不能添加自己为员工');
        }

        $params['user_id'] = $this->auth->id;
        $count = StaffModel::where([
            'user_id' => $params['user_id'],
            'mobile' => $params['mobile']
        ])->count();

        if ($count) {
            $this->error('该手机号已经添加过');
        }

        $user = \app\common\model\User::where('mobile', $params['mobile'])->find();
        if (empty($user)) {
            $this->error('员工未注册');
        }
        $s_data = Db::name("staff")->where(['mobile'=>$params['mobile']])->find();
        if($s_data){
            $this->error("该员工已被绑定");
        }
        Db::startTrans();
        try {
            $build_id_arr = explode(',',$params['build_ids']);
            //var_dump($build_id_arr);
            foreach ($build_id_arr as $k=>$v){
                //echo $v;
                $bu_data = Db::name("building")->where(['id'=>$v])->find();
                Db::name("building")->where(['id'=>$v])->update(['user_id'=>$bu_data['user_id'].','.$user->id]);
                $zone_data = Db::name("building_zone")->where(['id'=>$bu_data['zone_id']])->find();
                Db::name("building_zone")->where(['id'=>$bu_data['zone_id']])->update(['user_id'=>$zone_data['user_id'].','.$user->id]);
                //Db::name("building_zone")->insertGetId(['name'=>$zone_data['name'],'user_id'=>$user->id,'create_time'=>time()]);
            }
            StaffModel::create($params, true);

            if ($user->is_house_owner == 0) {
                // 自动生成房东认证
                $salt = Random::alnum();
                $password = substr($params['mobile'], -6);
                $password = $this->auth->getEncryptPassword($password, $salt);

                HouseOwnerModel::create([
                    'real_name' => $params['name'],
                    'card_no' => $params['id_card'] ?? '',
                    'status' => 1,
                    'user_id' => $user->id,
                    'password' => $password,
                    'salt' => $salt,
                    'password_time' => date('Y-m-d H:i:s'),
                ], true);


                $user->is_house_owner = 1;
                $user->save();

            }



            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            trace('添加员工失败：' . $e->getMessage() . $e->getTraceAsString(), 'error');
            $this->error($e->getMessage());
        }
        $this->success('保存成功');

    }


    public function info()
    {
        $id = $this->request->param('id/d');
        if ($id < 1) {
            $this->error('id错误');
        }
        $row = StaffModel::get($id);
        if (empty($row)) {
            $this->error('数据不存在');
        }

        $this->success('成功', $row);
    }


    public function del()
    {
        $id = $this->request->param('id/d');
        if ($id < 1) {
            $this->error('id错误');
        }
        $row = StaffModel::get($id);
        if (empty($row)) {
            $this->error('数据不存在');
        }
        $u_user_data = Db::name("user")->where(['mobile'=>$row['mobile']])->find();
        $build_id_arr = explode(',',$row->build_ids);
        foreach ($build_id_arr as $k=>$v){
            $bu_data = Db::name("building")->where(['id'=>$v])->find();
            $user_id_arr = explode(',',$bu_data['user_id']);
            $u_shan = [$u_user_data['id']];
            $array = array_diff($user_id_arr, $u_shan);
            $bu_end_str = implode(',',$array);
            Db::name("building")->where(['id'=>$v])->update(['user_id'=>$bu_end_str]);
            $zone_data = Db::name("building_zone")->where(['id'=>$bu_data['zone_id']])->find();
            $zone_user_id_arr = explode(',',$zone_data['user_id']);
            $u_shan = [$u_user_data['id']];
            $zone_array = array_diff($zone_user_id_arr, $u_shan);
            $zone_end_str = implode(',',$zone_array);
            Db::name("building_zone")->where(['id'=>$v])->update(['user_id'=>$zone_end_str]);
        }

        $row->delete();
        //Auth::instance()->delete($row['id']);
        $this->success('成功');
    }

    public function login_log()
    {
        $id = $this->request->param('id/d');
        if ($id < 1) {
            $this->error('id错误');
        }
        $page_size = $this->request->param('page_size', 10);
        $create_time = $this->request->param('create_time', '');
        $where = [];
        if (!empty($create_time)) {
            $range = explode(' - ', $create_time);
            $where['create_time'] = ['between', $range];
        }

        $staff = StaffModel::get($id);
        $staff_user_id = \app\common\model\User::where('mobile', $staff->mobile)->value('id', 0);
        $list = UserLoginLogModel::where('user_id', $staff_user_id)
            ->where($where)
            ->field('id,ip,create_time')
            ->order('id', 'desc')
            ->paginate($page_size)->each(function ($item) {

            });

        $this->success('success', $list);
    }
}
